import { validatenull } from '@/util/validate'
// 配置API接口地址
const baseUrl = 'http://47.96.66.69:4000' // 开发环境
// const baseUrl = 'http://47.96.66.69:9999' // 开发环境
// const baseUrl = 'http://192.168.0.115:4000' // 开发环境-甘雨
// const baseUrl = 'http://192.168.0.114:4000' // 开发环境-黄任兵
// const baseUrl = 'http://192.168.0.140:9999' // 开发环境-何南城

// 引入 弹窗组件
const modal = weex.requireModule('modal')
const storage = weex.requireModule('storage')
// 引入 请求数据组件

// 自定义判断元素类型JS
function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

// 参数过滤函数
function filterNull (o) {
  for (let key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}

// 工具方法
function toParams (obj) {
  let param = ''
  for (const name in obj) {
    if (typeof obj[name] !== 'function') {
      param += '&' + name + '=' + encodeURI(obj[name])
    }
  }
  return param.substring(1)
}

/**
 * 接口处理函数
 */

function doQuery (method, url, params, success, failure) {
  const stream = weex.requireModule('stream')
  if (method === 'GET') {
    // GET 方法
    let otherUrl = ''
    if (!validatenull(params)) {
      otherUrl = '?' + toParams(params)
    }
    stream.fetch({
      method: 'GET',
      type: 'json',
      url: baseUrl + url + otherUrl,
      timeout: 30000
    }, function (res) {
      callback(res, success, failure)
    })
  } else if (method === 'POST') {
    // POST 方法
    stream.fetch({
      method: 'POST',
      type: 'json',
      url: baseUrl + url,
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(params),
      timeout: 30000
    }, function (res) {
      callback(res, success, failure)
    })
  }
}

function apiStream (method, url, params, success, failure, needLogin) {
  // 过滤参数
  if (params) {
    params = filterNull(params)
  }
  if (needLogin) {
    storage.getItem('userId', event => {
      if (event.result === 'success') {
        params.userId = event.data
        doQuery(method, url, params, success, failure)
      } else {
        modal.toast({
          message: '用户未登录',
          duration: 0.8
        })
        const router = require('@/router')
        router.push('/login')
      }
    })
  } else {
    doQuery(method, url, params, success, failure)
  }
}

function callback (res, success, failure) { // 回调函数
  if (res.ok) {
    let data = res.data
    if (data.code === '0') {
      success(res.data)
    } else if (data.code === '00027') {
      storage.removeItem('userId', event => {
        if (event.result === 'success') {
          const router = require('@/router')
          router.push('/login')
        }
      })
    } else {
      modal.toast({
        message: data.msg,
        duration: 0.8
      })
      if (failure) {
        failure(res)
      }
      if (data.code === '00004') {
        const router = require('@/router')
        router.push('/login')
      }
    }
  } else {
    modal.toast({
      message: res.status + res.statusText,
      duration: 0.8
    })
    if (failure) {
      failure(res)
    }
  }
}

// 返回在vue模板中的调用接口
export default {
  get: function (url, params, success, failure, needLogin) {
    return apiStream('GET', url, params, success, failure, needLogin)
  },
  post: function (url, params, success, failure, needLogin) {
    return apiStream('POST', url, params, success, failure, needLogin)
  },
  url: baseUrl
}
